//
//  UIBarButtonItem+Extension.swift
//  Weibo12
//
//  Created by HM on 15/12/26.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit


extension UIBarButtonItem {

    // 在分类里面添加构造函数，用便利构造函数
    // Swift 函数的参数可以给定一个默认值，外界可以不传这个参数，就使用默认值
    convenience init(imageName: String? = nil, title: String? = nil, target: AnyObject?, action: Selector) {
        self.init()
        // 初始化一个按钮
        let button = UIButton()
        button.addTarget(target, action: action, forControlEvents: UIControlEvents.TouchUpInside)

        if imageName != nil {
            // 设置按钮的不同状态的图片
            button.setImage(UIImage(named: imageName!), forState: UIControlState.Normal)
            button.setImage(UIImage(named: "\(imageName!)_highlighted"), forState: UIControlState.Highlighted)
        }
        
        // 如果外界传入标题，就设置标题
        if title != nil {
            button.setTitle(title, forState: UIControlState.Normal)
            // 设置字体的大小颜色
            button.titleLabel?.font = UIFont.systemFontOfSize(15)
            button.setTitleColor(UIColor(white: 80/255, alpha: 1), forState: UIControlState.Normal)
            button.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Highlighted)
        }

        // 设置按钮的大小
        button.sizeToFit()
        // 将按钮设置成当前类的 customView
        customView = button
    }
}
